import 'package:get/get.dart';
import 'package:flutter/foundation.dart';
import '../../../core/network/api_provider.dart';
import '../../../core/errors/exceptions.dart';
import '../models/response/base_response.dart';
import '../models/response/api_error.dart';
import '../../constants/api_constants.dart';

/// 数据提供者基类
/// 封装了 GetConnect 并提供基础的错误处理
abstract class BaseProvider extends GetConnect {
  // 依赖注入核心 ApiProvider (通常包含 Dio 或 http 实例)
  final ApiProvider _apiProvider = Get.find<ApiProvider>();

  @override
  void onInit() {
    super.onInit();
    
    // 配置 GetConnect
    // httpClient.baseUrl = _apiProvider.baseUrl; // 从 ApiProvider 获取基础 URL
    // httpClient.timeout = _apiProvider.timeout; // 设置超时
    
    // 添加拦截器（如果需要，也可以在 ApiProvider 中统一处理）
    // httpClient.addRequestModifier<dynamic>((request) {
    //   // 添加认证头等
    //   return request;
    // });
    
    // httpClient.addResponseModifier((request, response) {
    //   // 基础响应处理
    //   return response;
    // });
  }

  /// 处理 API 响应并返回 BaseResponse
  /// 
  /// [request] 是执行 API 请求的 Future 函数
  /// [fromJson] 是将响应数据转换为模型 T 的函数
  Future<BaseResponse<T>> handleResponse<T>(
    Future<Response<dynamic>> Function() request,
    T Function(Object? json) fromJson,
  ) async {
    try {
      final Response<dynamic> response = await request();

      if (response.statusCode == 200 || response.statusCode == 201) {
        if (response.body != null) {
          // 尝试将响应体解析为 BaseResponse 结构
          if (response.body is Map<String, dynamic>) {
            return BaseResponse<T>.fromJson(response.body, fromJson);
          } else {
            // 如果响应体不是预期的 Map 结构，则视为错误
            return BaseResponse.error(
              response.statusCode.toString(),
              'Invalid response format', 
            );
          }
        } else {
          // 响应体为空
          return BaseResponse.error(
            response.statusCode.toString(),
            'Empty response body',
          );
        }
      } else {
        // 处理 HTTP 错误状态码
        String errorMessage = 'HTTP Error: ${response.statusCode}';
        if (response.body != null && response.body['message'] != null) {
          errorMessage = response.body['message'] as String;
        }
        return BaseResponse.error(
          response.statusCode.toString(),
          errorMessage,
        );
      }
    } catch (e) {
      // 处理请求过程中的异常（网络错误、超时、解析错误等）
      debugPrint('API Request Error: $e');
      final apiError = ApiError.fromException(e);
      return BaseResponse.error(
        apiError.code.toString(),
        apiError.message,
      );
    }
  }
  
  /// 简化 GET 请求的处理
  Future<BaseResponse<T>> getRequest<T>(
    String url,
    T Function(Object? json) fromJson,
    {Map<String, String>? headers, Map<String, dynamic>? query}
  ) {
    return handleResponse(() => get(url, headers: headers, query: query), fromJson);
  }
  
  /// 简化 POST 请求的处理
  Future<BaseResponse<T>> postRequest<T>(
    String url,
    dynamic body,
    T Function(Object? json) fromJson,
    {Map<String, String>? headers, Map<String, dynamic>? query}
  ) {
    return handleResponse(() => post(url, body, headers: headers, query: query), fromJson);
  }
  
  /// 执行GET请求
  Future<BaseResponse<T>> get<T>(
    String url, {
    Map<String, dynamic>? query,
    Map<String, String>? headers,
    T Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _apiProvider.get(
        url,
        query: query,
        headers: headers,
      );
      
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }
  
  /// 执行POST请求
  Future<BaseResponse<T>> post<T>(
    String url, {
    dynamic body,
    Map<String, dynamic>? query,
    Map<String, String>? headers,
    T Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _apiProvider.post(
        url,
        body: body,
        query: query,
        headers: headers,
      );
      
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }
  
  /// 执行PUT请求
  Future<BaseResponse<T>> put<T>(
    String url, {
    dynamic body,
    Map<String, dynamic>? query,
    Map<String, String>? headers,
    T Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _apiProvider.put(
        url,
        body: body,
        query: query,
        headers: headers,
      );
      
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }
  
  /// 执行DELETE请求
  Future<BaseResponse<T>> delete<T>(
    String url, {
    dynamic body,
    Map<String, dynamic>? query,
    Map<String, String>? headers,
    T Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _apiProvider.delete(
        url,
        body: body,
        query: query,
        headers: headers,
      );
      
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }
  
  /// 执行PATCH请求
  Future<BaseResponse<T>> patch<T>(
    String url, {
    dynamic body,
    Map<String, dynamic>? query,
    Map<String, String>? headers,
    T Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _apiProvider.patch(
        url,
        body: body,
        query: query,
        headers: headers,
      );
      
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }
  
  /// 处理响应
  BaseResponse<T> _handleResponse<T>(
    dynamic response,
    T Function(dynamic)? fromJson,
  ) {
    if (response is Map<String, dynamic>) {
      return BaseResponse<T>.fromJson(response, fromJson);
    }
    
    return BaseResponse<T>.error(
      ApiConstants.errorCodes.failure,
      '无效的响应格式',
    );
  }
  
  /// 处理错误
  BaseResponse<T> _handleError<T>(dynamic error) {
    if (error is ServerException) {
      return BaseResponse<T>.error(
        error.code ?? ApiConstants.errorCodes.serverError,
        error.message,
      );
    } else if (error is UnauthorizedException) {
      return BaseResponse<T>.error(
        error.code ?? ApiConstants.errorCodes.unauthorized,
        error.message,
      );
    } else if (error is NetworkException) {
      return BaseResponse<T>.error(
        ApiConstants.errorCodes.failure,
        error.message,
      );
    } else if (error is CacheException) {
      return BaseResponse<T>.error(
        ApiConstants.errorCodes.failure,
        error.message,
      );
    } else {
      return BaseResponse<T>.error(
        ApiConstants.errorCodes.failure,
        error.toString(),
      );
    }
  }
  
  /// 获取列表数据
  Future<BaseResponse<List<T>>> getList<T>(
    String url, {
    Map<String, dynamic>? query,
    Map<String, String>? headers,
    required T Function(Map<String, dynamic>) fromJson,
  }) async {
    try {
      final response = await _apiProvider.get(
        url,
        query: query,
        headers: headers,
      );
      
      if (response is Map<String, dynamic>) {
        return BaseResponse.fromJsonList<T>(response, fromJson);
      }
      
      return BaseResponse<List<T>>.error(
        ApiConstants.errorCodes.failure,
        '无效的响应格式',
      );
    } catch (e) {
      if (e is UnauthorizedException) {
        return BaseResponse<List<T>>.error(
          ApiConstants.errorCodes.unauthorized,
          e.message,
        );
      }
      
      return BaseResponse<List<T>>.error(
        ApiConstants.errorCodes.failure,
        e.toString(),
      );
    }
  }
  
  /// 获取分页数据
  Future<BaseResponse<Pagination<T>>> getPagination<T>(
    String url, {
    Map<String, dynamic>? query,
    Map<String, String>? headers,
    required T Function(Map<String, dynamic>) fromJson,
  }) async {
    try {
      final response = await _apiProvider.get(
        url,
        query: query,
        headers: headers,
      );
      
      if (response is Map<String, dynamic>) {
        return BaseResponse.fromJsonPagination<T>(response, fromJson);
      }
      
      return BaseResponse<Pagination<T>>.error(
        ApiConstants.errorCodes.failure,
        '无效的响应格式',
      );
    } catch (e) {
      if (e is UnauthorizedException) {
        return BaseResponse<Pagination<T>>.error(
          ApiConstants.errorCodes.unauthorized,
          e.message,
        );
      }
      
      return BaseResponse<Pagination<T>>.error(
        ApiConstants.errorCodes.failure,
        e.toString(),
      );
    }
  }
} 